package com.thread;

import java.util.concurrent.Semaphore;

public class Solution1226 {
}

class DiningPhilosophers {

    Semaphore s = new Semaphore(4);
    Semaphore[] ss = new Semaphore[5];

    public DiningPhilosophers() {
        for (int i = 0; i < 5; i++) {
            ss[i] = new Semaphore(1);
        }
    }

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
        s.acquire();
        ss[philosopher].acquire();
        ss[(philosopher + 1) % 5].acquire();
        pickLeftFork.run();
        pickRightFork.run();
        eat.run();
        putLeftFork.run();
        putRightFork.run();
        ss[philosopher].release();
        ss[(philosopher + 1) % 5].release();
        s.release();
    }
}
